<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="description" content="PragmaticScala">
<meta name="generator" content="Paradox, paradox-material-theme=0.5.1, mkdocs-material=3.0.3">

<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="">
<meta name="lang:search.pipeline.stopwords" content="true">
<meta name="lang:search.pipeline.trimmer" content="true">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">


<meta name="description" content="PragmaticScala">
<link rel="shortcut icon" href="../assets/images/favicon.png">
<title>第10章——处理异常 · </title>
<link rel="stylesheet" href="../assets/stylesheets/application.451f80e5.css">
<link rel="stylesheet" href="../lib/material__tabs/dist/mdc.tabs.min.css">
<link rel="stylesheet" href="../lib/prettify/prettify.css">
<script src="../assets/javascripts/modernizr.1aa3b519.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700|Roboto+Mono">
<style>
body,input{font-family:"Roboto","Helvetica Neue",Helvetica,Arial,sans-serif}
code,kbd,pre{font-family:"Roboto Mono","Courier New",Courier,monospace}
</style>
<link rel="stylesheet" href="../assets/fonts/font-awesome.css">
<link rel="stylesheet" href="../assets/fonts/material-icons.css">
<link rel="stylesheet" href="../assets/stylesheets/paradox-material-theme.css">
</head>
<body
>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer" autocomplete="off">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search" autocomplete="off">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="" class="md-header-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">
</span>
<span class="md-header-nav__topic">
第10章——处理异常
</span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" name="search">
<input type="text" class="md-search__input" name="query" placeholder="Search" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">&#xE5CD;</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>

</div>
</div>
</nav>
</header>

<div class="md-container">
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0" style="visibility: hidden">
<label class="md-nav__title md-nav__title--site" for="drawer">
<a href="../index.html" title="" class="md-nav__button md-logo">
<span class="md-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
<a href="../index.html" title="">
</a>
</label>
<ul>
  <li><a href="../contents.html" class="page">目录</a>
  <ul>
    <li><a href="../abstract.html" class="page">内容提要</a></li>
    <li><a href="../part1.html" class="page">第一部分 小试牛刀</a></li>
    <li><a href="../part2.html" class="page">第二部分 深入 Scala</a></li>
    <li><a href="../part3.html" class="page">第三部分 Scala 中的并发编程</a></li>
    <li><a href="../part4.html" class="page">第四部分 Scala 实战</a></li>
    <li><a href="../refs/references.html" class="page">参考书目</a></li>
    <li><a href="../extras.html" class="page">额外指引</a></li>
    <li><a href="../errata.html" class="page">勘误</a></li>
  </ul></li>
</ul>
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../chapter-10/index.html#第10章-处理异常" class="header">第10章——处理异常</a>
  <ul>
    <li><a href="../chapter-10/index.html#10-1-scala-中的异常" class="header">10.1 Scala 中的异常</a></li>
    <li><a href="../chapter-10/index.html#10-2-注意-catch-的顺序" class="header">10.2 注意 catch 的顺序</a></li>
  </ul></li>
</ul>
</nav>

</nav>
<ul style="display: none">
<li class="md-nav__item md-version" id="project.version">
<label class="md-nav__link" for="__version">
<i class="md-icon" title="Version">label_outline</i> 1.0.0
</label>
</li>
</ul>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../chapter-10/index.html#第10章-处理异常" class="header">第10章——处理异常</a>
  <ul>
    <li><a href="../chapter-10/index.html#10-1-scala-中的异常" class="header">10.1 Scala 中的异常</a></li>
    <li><a href="../chapter-10/index.html#10-2-注意-catch-的顺序" class="header">10.2 注意 catch 的顺序</a></li>
  </ul></li>
</ul>
</nav>

</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset">
<div class="md-content__searchable">
<h1><a href="#第10章-处理异常" name="第10章-处理异常" class="anchor"><span class="anchor-link"></span></a>第10章——处理异常</h1>
<p>Java 的受检异常（checked exception）会强制开发人员捕获错误，包括那些开发人员并不关 心的，因此 Java 程序员经常会写一个空的 catch 代码块来抑制相关的异常，而不是将其引渡至 合理的位置上进行处理。Scala 不这样做。它让开发人员只处理自己关心的异常，并忽略其他异 常。这些没有处理的异常将会自动地传播。在本章中，我们将学到如何在 Scala 中处理异常。</p>
<h2><a href="#10-1-scala-中的异常" name="10-1-scala-中的异常" class="anchor"><span class="anchor-link"></span></a>10.1 Scala 中的异常</h2>
<blockquote>
  <p>ExceptionHandling/Throw.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">throw new IllegalArgumentException</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter10/Throw.scala#L21">Full source at GitHub</a>
<blockquote>
  <p>ExceptionHandling/JavaThreadSleep.java</p>
</blockquote>
<pre class="prettyprint"><code class="language-java">  // Java code
try {
  Thread.sleep(1000);
}                    
catch(InterruptedException ex) {
  // Losing sleep over what to do here?
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter10/JavaThreadSleep.java#L22-L28">Full source at GitHub</a>
<blockquote>
  <p>ExceptionHandling/ThreadSleep.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">Thread.sleep(1000)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter10/ThreadSleep.scala#L21">Full source at GitHub</a>
<blockquote>
  <p>ExceptionHandling/Tax.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">object Tax {
  def taxFor(amount: Double): Double = {
    if (amount &lt; 0)
      throw new IllegalArgumentException(&quot;Amount must be greater than zero&quot;)

    if (amount &lt; 0.01)
      throw new RuntimeException(&quot;Amount too small to be taxed&quot;)

    if (amount &gt; 1000000) throw new Exception(&quot;Amount too large...&quot;)

    amount * 0.08
  }
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter10/Tax.scala#L20-L32">Full source at GitHub</a>
<blockquote>
  <p>ExceptionHandling/ExceptionHandling.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">for (amount ← List(100.0, 0.009, -2.0, 1000001.0)) {
  try {
    print(s&quot;Amount: $$$amount &quot;)
    println(s&quot;Tax: $$${Tax.taxFor(amount)}&quot;)
  } catch {
    case ex: IllegalArgumentException ⇒ println(ex.getMessage)
    case ex: RuntimeException ⇒
      // if you need a block of code to handle exception
      println(s&quot;Don&#39;t bother reporting...${ex.getMessage}&quot;)
  }
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter10/ExceptionHandling.scala#L21-L31">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">Amount: $100.0 Tax: $8.0
Amount: $0.009 Don&#39;t bother reporting...Amount too small to be taxed
Amount: $-2.0 Amount must be greater than zero
Amount: $1000001.0 java.lang.Exception: Amount too large...
	at Tax$.taxFor(Tax.scala:9)
...</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter10/shoutput/RunExceptionHandling.output#L2-L7">Full source at GitHub</a>
<blockquote>
  <p>ExceptionHandling/CatchAll.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">for (amount ← List(100.0, 0.009, -2.0, 1000001.0)) {
  try {
    print(s&quot;Amount: $$$amount &quot;)
    println(s&quot;Tax: $$${Tax.taxFor(amount)}&quot;)
  } catch {
    case ex: IllegalArgumentException ⇒ println(ex.getMessage)
    case _: Throwable                 ⇒ println(&quot;Something went wrong&quot;)
  }
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter10/CatchAll.scala#L22-L30">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">Amount: $100.0 Tax: $8.0
Amount: $0.009 Something went wrong
Amount: $-2.0 Amount must be greater than zero
Amount: $1000001.0 Something went wrong</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter10/shoutput/RunCatchAll.output#L2-L5">Full source at GitHub</a>
<h2><a href="#10-2-注意-catch-的顺序" name="10-2-注意-catch-的顺序" class="anchor"><span class="anchor-link"></span></a>10.2 注意 catch 的顺序</h2>
<blockquote>
  <p>ExceptionHandling/JavaCatchOrder.java</p>
</blockquote>
<pre class="prettyprint"><code class="language-java">// Java code—will not compile due to incorrect catch order
public class JavaCatchOrder {
  public void catchOrderExample() {
    try {
      String str = &quot;hello&quot;;
      System.out.println(str.charAt(31));
    } catch (Exception ex) {
      System.out.println(&quot;Exception caught&quot;);
    } catch (StringIndexOutOfBoundsException ex) { //ERROR
      System.out.println(&quot;Invalid Index&quot;);
    }
  }
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/test/java/chapter10/JavaCatchOrder.java#L18-L30">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">JavaCatchOrder.java:10: error: exception StringIndexOutOfBoundsException
has already been caught
    catch(StringIndexOutOfBoundsException ex) { //ERROR
    ^
1 error</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter10/compileroutput/JavaCatchOrder.output#L2-L6">Full source at GitHub</a>
<blockquote>
  <p>ExceptionHandling/CatchOrder.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val amount = -2
try {
  print(s&quot;Amount: $$$amount &quot;)
  println(s&quot;Tax: $$${Tax.taxFor(amount)}&quot;)
} catch {
  case _: Exception                 ⇒ println(&quot;Something went wrong&quot;)
  case ex: IllegalArgumentException ⇒ println(ex.getMessage)
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter10/CatchOrder.scala#L22-L29">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">Amount: $-2 Something went wrong</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter10/shoutput/RunCatchOrder.output#L2">Full source at GitHub</a>
</div>
<div>
<a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/master/src/paradox/chapter-10/index.md" title="Edit this page" class="md-source-file md-edit">
Edit this page
</a>
</div>
<div class="print-only">
<span class="md-source-file md-version">
1.0.0
</span>
</div>
</article>
</div>
</div>
</main>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="../chapter-09/index.html" title="第9章——模式匹配和正则表达式" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Previous
</span>
第9章——模式匹配和正则表达式
</span>
</div>
</a>
<a href="../chapter-11/index.html" title="第11章——递归编程" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Next
</span>
第11章——递归编程
</span>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
Powered by
<a href="https://github.com/lightbend/paradox">Paradox</a>
and
<a href="https://jonas.github.io/paradox-material-theme/">Paradox Material Theme</a>

</div>
</div>
</div>
</footer>

</div>
<script src="../assets/javascripts/application.583bbe55.js"></script>
<script src="../assets/javascripts/paradox-material-theme.js"></script>
<script>app.initialize({version:"0.17",url:{base:"../."}})</script>
<script type="text/javascript" src="../lib/prettify/prettify.js"></script>
<script type="text/javascript" src="../lib/prettify/lang-scala.js"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
window.prettyPrint && prettyPrint();
});
</script>
</body>
</html>
